package com.bskj.bms.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.bskj.bms.bean.req.BasePageListReqVo;
import com.bskj.bms.bean.req.BillListReqVo;
import com.bskj.bms.bean.vo.ShopCouponVo;
import com.bskj.bms.bean.vo.UserCouponReleaseRespVo;
import com.bskj.bms.service.IBmsCouponService;
import com.bskj.bms.service.IBmsShopService;
import com.bskj.bms.service.IShortUrlService;
import com.bskj.common.bean.model.BmsUser;
import com.bskj.common.bean.model.ParkingLotCustomer;
import com.bskj.common.bean.model.ParkingShop;
import com.bskj.common.bean.model.ShopCoupon;
import com.bskj.common.bean.model.ShortUrl;
import com.bskj.common.bean.model.UserCoupon;
import com.bskj.common.dao.core.Page;
import com.bskj.common.enums.BmsUserTypeEnum;
import com.bskj.common.enums.ShopCouponValidTypeEnum;
import com.bskj.common.utils.EncryptUtil;
import com.bskj.common.utils.Global;
import com.bskj.common.utils.HttpRequestUtil;
import com.bskj.common.utils.QrCodeCreateUtil;
import com.bskj.common.utils.ShortUrlUtil;
import com.bskj.common.utils.StringUtils;

@Controller
@RequestMapping("/coupon")
public class CouponController extends BaseController{
	
	@Autowired
	private IBmsCouponService bmsCouponService;
	
	@Autowired
	private IShortUrlService shortUrlService;
	
	@Autowired
	private IBmsShopService bmsShopService;
	
	@RequestMapping("/index")
	public ModelAndView index(Integer shopId) {
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/coupon/index");
		mv.addObject("shopId", shopId);
		return mv;
	}
	
	@RequestMapping("/toAddCoupon")
	public ModelAndView toAddCoupon(Integer shopId,@RequestParam(required = false) Integer couponId) {
		ModelAndView mv=new ModelAndView();
		if(couponId != null){
			ShopCoupon shopCoupon=bmsCouponService.get(couponId);
			mv.addObject("shopCoupon", shopCoupon);
		}
		mv.setViewName("/coupon/addCoupon");
		mv.addObject("shopId", shopId);
		return mv;
	}
	
	@RequestMapping("/toDelCoupon")
	public ModelAndView toDelCoupon(@RequestParam(required = false) Integer id) {
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/coupon/delCoupon");
		mv.addObject("id", id);
		return mv;
	}
	
	@ResponseBody
	@RequestMapping("delete")
	public Map<String, Object> delete(@RequestParam(required = false) Integer id) {
		Map<String, Object> resultMap=new HashMap<>();
		try {
			bmsCouponService.del(id);
			resultMap.put("success",true);
			resultMap.put("meg","删除成功！");
		} catch (Exception e) {
			resultMap.put("success", false);
			resultMap.put("meg","删除失败，请稍后重试！");
			e.printStackTrace();
			return resultMap;
		}
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping("list")
	public Map<String, Object> list(BasePageListReqVo req) throws Exception {
		Map<String, Object> resultMap=new HashMap<>();
		
		Page<ShopCouponVo> shopCouponPage=bmsCouponService.findAllCoupon(getSessionUser().getCustId(),req);
		resultMap.put("data", shopCouponPage.getList());
		resultMap.put("draw", req.getDraw());
		resultMap.put("recordsTotal", shopCouponPage.getList().size());
		resultMap.put("recordsFiltered", shopCouponPage.getTotalRow());
		
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping("addCoupon")
	public Map<String, Object> addCoupon(ShopCouponVo req) throws Exception {
		Map<String, Object> resultMap=new HashMap<>();
		if(req.getId() == null){
			bmsCouponService.addCoupon(req,getSessionUser().getCustId());
		}else {
			ShopCoupon shopCoupon = bmsCouponService.get(req.getId());
			shopCoupon.setId(req.getId());
			shopCoupon.setMoney(req.getMoney());
			shopCoupon.setValidType(req.getValidType());
			shopCoupon.setValidTime(req.getValidTime());
			shopCoupon.setLastTime(req.getLastTime());
			shopCoupon.setParkingLotCustomerId(getSessionUser().getCustId());
			shopCoupon.setStatus(1);
			shopCoupon.setCouponMoneyType(req.getCouponMoneyType());
			shopCoupon.setShopId(req.getShopId());
			shopCoupon.setUpdateTime(new Date());
			bmsCouponService.update(shopCoupon);
		}
		
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping("changeStatus")
	public Map<String, Object> list(Integer id,int status) throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		ShopCoupon coupon = bmsCouponService.get(id);
		if(coupon == null) {
			resultMap.put("success", false);
			resultMap.put("msg", "停车券不存在");
			return resultMap;
		} else {
			if(BmsUserTypeEnum.get(status) == null) {
				resultMap.put("success", false);
				resultMap.put("msg", "请求参数不合法");
				return resultMap;
			}
			coupon.setStatus(status);
			coupon.setUpdateTime(new Date());
			bmsCouponService.update(coupon);
			resultMap.put("success", true);
		}
		return resultMap;
	}
	
	
	@RequestMapping("/toShopCoupon")
	public ModelAndView toShopCoupon() {
		ModelAndView mv =new ModelAndView();
		mv.setViewName("/coupon/shopCoupon");
		return mv;
	}
	
	@ResponseBody
	@RequestMapping("shopCoupon")
	public Map<String, Object> shopCoupon(BillListReqVo req) throws Exception {
		Map<String, Object> resultMap=new HashMap<>();
		BmsUser bmsUser=getSessionUser();
		Page<UserCouponReleaseRespVo> userCouponReleaseRespVos= new Page<>();
		if(bmsUser.getType() == BmsUserTypeEnum.parking_shop_user.getKey()){
			userCouponReleaseRespVos.setList(bmsCouponService.shopCoupon(req , bmsUser.getShopId()));
			userCouponReleaseRespVos.setTotalRow(1);
		}else if (bmsUser.getType() == BmsUserTypeEnum.parking_lot_user.getKey()) {
			userCouponReleaseRespVos=bmsCouponService.shopsCoupon(req , bmsUser.getCustId());
		}
		resultMap.put("data", userCouponReleaseRespVos.getList());
		resultMap.put("draw", req.getDraw());	
		resultMap.put("recordsTotal", userCouponReleaseRespVos.getList().size());
		resultMap.put("recordsFiltered", userCouponReleaseRespVos.getTotalRow());
		return resultMap;
	}
	
	
	@RequestMapping("/toGeneralQRCode")
	public ModelAndView toGeneralQRCode(Integer couponId) {
		ModelAndView mv =new ModelAndView();
		
		ShopCoupon shopCoupon=bmsCouponService.get(couponId);
		UserCoupon userCoupon=new UserCoupon();	
		try {
			userCoupon.setUuid(StringUtils.getRandomWithTimestamp(21));
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		userCoupon.setCouponId(shopCoupon.getId());
		userCoupon.setParkingLotCustomerId(shopCoupon.getParkingLotCustomerId());
		userCoupon.setCouponMoneyType(shopCoupon.getCouponMoneyType());
		userCoupon.setMoney(shopCoupon.getMoney());
		userCoupon.setValidType(shopCoupon.getValidType());
		userCoupon.setShopId(shopCoupon.getShopId());
		userCoupon.setStatus(0);
		
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("userCouponEncryptStr", userCoupon.toEncryptJSONString());
			jsonObject.put("shopId", shopCoupon.getShopId());
			String url = Global.getConfig("WX_GET_QRCODE_URL");
			Map<String, Object> params = new HashMap<>();
			params.put("actionUrl", "/userCoupon/page/receiveCouponIndex");
			params.put("jsonStr", jsonObject.toString());
			String wxAccountid = Global.getConfig("KUAIFU_WX_ACCOUNTID");
			String appKey = EncryptUtil.encrypt(wxAccountid);
			params.put("appKey", appKey);
			String urlContent = HttpRequestUtil.httpClientPost(url, params);
			String shortUrl = ShortUrlUtil.shortUrl(urlContent);// https://kuaifu.boshukeji.com/short/{shortUrl}
			String newUrl = Global.getConfig("SJ_SHORT_URL") + "/" + shortUrl;
			ShortUrl t = new ShortUrl();
			t.setShortUrl(shortUrl);
			t.setActionUrl(urlContent);
			t.setCreateTime(new Date());
			shortUrlService.insert(t);
			String qrcodeStream = QrCodeCreateUtil.generalQRCode(newUrl);
			mv.addObject("qrcodeStream", qrcodeStream);
			mv.setViewName("coupon/generalQRCode");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mv;
	}
	
	
	@RequestMapping("/toGeneralQRCodes")
	public ModelAndView toGeneralQRCodes(Integer couponId) throws Exception {
		ShopCoupon shopCoupon=bmsCouponService.get(couponId);
		ModelAndView mv =new ModelAndView();
		ParkingLotCustomer parkingLotCustomer=shortUrlService.findParking(shopCoupon.getParkingLotCustomerId());
		if(shopCoupon.getValidType()==ShopCouponValidTypeEnum.coupon_crtain.getKey()){
			double time=shopCoupon.getValidTime();
			int hour=(int)time;
			mv.addObject("prompt","需在"+hour+"小时"+(int)((time-hour)*60)+"分钟前微信扫码使用");
		}else {
			mv.addObject("prompt","需在当日"+shopCoupon.getLastTime()+"前微信扫码使用");
		}
		ParkingShop parkingShop=bmsShopService.get(shopCoupon.getShopId());
		
		if(shopCoupon.getCouponMoneyType() == 1){
			mv.addObject("coupons",parkingShop.getName()+shopCoupon.getMoney()/10+"元停车券" );
		}else {
			mv.addObject("coupons",parkingShop.getName()+"免费停车券" );
		}
		
		mv.addObject("parkName", parkingLotCustomer.getParkingName());
		mv.addObject("couponId", couponId);
		mv.setViewName("coupon/generalQRCodes");
		return mv;
	}
	
	@RequestMapping("generalQRCode")
	@ResponseBody
	public Map<String, Object> generalQRCode(Integer couponId) throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		ShopCoupon shopCoupon=bmsCouponService.get(couponId);
		UserCoupon userCoupon=new UserCoupon();	
		try {
			userCoupon.setUuid(StringUtils.getRandomWithTimestamp(21));
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		userCoupon.setCouponId(shopCoupon.getId());
		userCoupon.setParkingLotCustomerId(shopCoupon.getParkingLotCustomerId());
		userCoupon.setCouponMoneyType(shopCoupon.getCouponMoneyType());
		userCoupon.setMoney(shopCoupon.getMoney());
		userCoupon.setValidType(shopCoupon.getValidType());
		userCoupon.setShopId(shopCoupon.getShopId());
		userCoupon.setStatus(0);
		
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("userCouponEncryptStr", userCoupon.toEncryptJSONString());
			jsonObject.put("shopId", shopCoupon.getShopId());
			String url = Global.getConfig("WX_GET_QRCODE_URL");
			Map<String, Object> params = new HashMap<>();
			params.put("actionUrl", "/userCoupon/page/receiveCouponIndex");
			params.put("jsonStr", jsonObject.toString());
			String wxAccountid = Global.getConfig("KUAIFU_WX_ACCOUNTID");
			String appKey = EncryptUtil.encrypt(wxAccountid);
			params.put("appKey", appKey);
			String urlContent = HttpRequestUtil.httpClientPost(url, params);
			String shortUrl = ShortUrlUtil.shortUrl(urlContent);// https://kuaifu.boshukeji.com/short/{shortUrl}
			String newUrl = Global.getConfig("SJ_SHORT_URL") + "/" + shortUrl;
			ShortUrl t = new ShortUrl();
			t.setShortUrl(shortUrl);
			t.setActionUrl(urlContent);
			t.setCreateTime(new Date());
			shortUrlService.insert(t);
			String qrcodeStream= QrCodeCreateUtil.generalQRCode(newUrl);
			resultMap.put("qrcodeStream", qrcodeStream);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resultMap.put("result", true);
		return resultMap;
	}
	
	
	@RequestMapping("/indexShop")
	public ModelAndView indexShop() throws Exception {
		ModelAndView mv=new ModelAndView();
		mv.setViewName("coupon/indexShop");
		mv.addObject("shopId", getSessionUser().getShopId());
		return mv;
	}
	
	@ResponseBody
	@RequestMapping("listShop")
	public Map<String, Object> listShop(BasePageListReqVo req) throws Exception {
		Map<String, Object> resultMap=new HashMap<>();
		Page<ShopCouponVo> shopCouponPage=bmsCouponService.findAllCoupon(getSessionUser().getCustId(),req);
		resultMap.put("data", shopCouponPage.getList());
		resultMap.put("draw", req.getDraw());
		resultMap.put("recordsTotal", shopCouponPage.getList().size());
		resultMap.put("recordsFiltered", shopCouponPage.getTotalRow());
		return resultMap;
	}
}
